import { fileURLToPath, URL } from 'node:url'
import { userInfo } from 'node:os'
import { defineConfig, loadEnv } from 'vite'
import vue from '@vitejs/plugin-vue'
import path from 'path'
import { createSvgIconsPlugin } from 'vite-plugin-svg-icons'
import vueJsx from '@vitejs/plugin-vue-jsx'
import AutoImport from 'unplugin-auto-import/vite'
import rollupPluginVisualizer from 'rollup-plugin-visualizer'
import vitePluginCompression from 'vite-plugin-compression'
import vitePluginCdnImport, { autoComplete } from 'vite-plugin-cdn-import'
import { ViteImageOptimizer } from 'vite-plugin-image-optimizer'

export default defineConfig(async ({ command, mode }) => {
  // 加载环境变量
  const env = loadEnv(mode, process.cwd(), 'VITE_')
  const envConfig = (await import('./env.js')).envs[mode]

  return {
    define: {
      'process.env': {
        VUE_APP_ENV: JSON.stringify(mode),
        NODE_ENV: JSON.stringify(mode),
        BASE_API: JSON.stringify(envConfig.BASE_API)
      },
      __PACK_DATETIME__: JSON.stringify(new Date().toLocaleString()),
      __PACK_USER__: JSON.stringify(userInfo().username),
      __BASE_API__: JSON.stringify(envConfig.BASE_API),
      __APP_CONFIG__: JSON.stringify({
        SYSTEM_NAME: envConfig.SYSTEM_NAME || '数据评估平台',
        BASE_URL: envConfig.BASE_URL || '/'
      })
    },
    
    base: envConfig.BASE_URL || '/',

    resolve: {
      alias: {
        '@': fileURLToPath(new URL('./src', import.meta.url)),
        '/@': fileURLToPath(new URL('./src', import.meta.url)),
        '~': fileURLToPath(new URL('./src/components', import.meta.url)),
      },
      extensions: ['.mjs', '.js', '.ts', '.jsx', '.tsx', '.json', '.vue'],
    },

    server: {
      port: envConfig.PORT || { development: 1024, test: 1025 }[mode],
      host: true,
      open: true,
      proxy: {
        '/api': {
          target: envConfig.BASE_API,
          changeOrigin: true,
          rewrite: (p) => p.replace(/^\/api/, ''),
        },
      },
    },

    build: {
      minify: 'terser',
      reportCompressedSize: false,
      terserOptions: {
        compress: {
          drop_console: true,
          drop_debugger: true,
        },
      },
      rollupOptions: {
        output: {
          assetFileNames: 'assets/[ext]/[name]-[hash][extname]',
          chunkFileNames: 'assets/js/[name]-[hash].js',
          manualChunks: (id) => {
            if (id.includes('assets/icons/svg')) {
              return 'icons-svg'
            } else if (['quill-image-resize-module', 'Quill'].some((e) => id.includes(e))) {
              return 'quill-image-resize-module'
            } else if (id.includes('node_modules')) {
              return id.split('node_modules/')[1].split('/')[0]
            }
          },
        },
      },
    },

    plugins: [
      vue(),
      createSvgIconsPlugin({
        iconDirs: [path.resolve(process.cwd(), 'src/assets/icons/svg')],
        symbolId: 'icon-[dir]-[name]',
      }),
      ViteImageOptimizer({
        png: { quality: 100 },
        jpeg: { quality: 100 },
        jpg: { quality: 100 },
      }),
      AutoImport({
        imports: ['vue', 'vue-router'],
      }),
      vueJsx(),
      vitePluginCompression({
        disable: !envConfig._ISGZIP,
        threshold: 10000,
      }),
      envConfig._ISCDN && vitePluginCdnImport({
        prodUrl: 'https://cdn.bootcdn.net/ajax/libs/{name}/{version}/{path}',
        modules: [
          {
            name: 'axios',
            var: 'axios',
            version: '1.4.0',
            path: 'axios.min.js',
          },
          {
            name: 'clipboard',
            var: 'ClipboardJS',
            version: '2.0.11',
            path: 'https://cdn.bootcdn.net/ajax/libs/clipboard.js/2.0.11/clipboard.min.js',
          },
          {
            name: 'jsencrypt',
            var: 'JSEncrypt',
            version: '3.3.2',
            path: 'jsencrypt.min.js',
          },
          {
            name: 'crypto-js',
            var: 'CryptoJS',
            version: '4.1.1',
            path: 'crypto-js.min.js',
          },
          {
            name: 'nprogress',
            var: 'NProgress',
            version: '0.2.0',
            path: 'nprogress.min.js',
            css: 'nprogress.min.css',
          },
          {
            name: 'ali-oss',
            var: 'OSS',
            path: 'https://gosspublic.alicdn.com/aliyun-oss-sdk-6.17.1.min.js',
          },
          {
            name: 'echarts',
            var: 'echarts',
            version: '5.4.2',
            path: 'echarts.min.js',
          },
        ],
      }),
      process.env.npm_config_report && rollupPluginVisualizer({
        emitFile: false,
        filename: 'report.html',
        open: false,
        gzipSize: true,
      }),
    ],
  }
})